package app.caihan.scframe.api.retrofit2

/**
 * 请求结果处理-密封类
 *
 * @author Seven-C
 * @date 2020/8/10
 */
sealed class ScResult<out R> {

    data class Success<out T>(val data: T) : ScResult<T>()
    data class Error(val throwable: ResponseThrowable) : ScResult<Nothing>()

    override fun toString(): String {
        return when (this) {
            is Success<*> -> {
                "Success[data=$data]"
            }
            is Error -> {
                "Error[throwable=$throwable]"
            }
        }
    }
}

/**
 * 直接返回请求成功结果
 */
inline fun <reified T> ScResult<T>.doSuccess(onSuccess: (T) -> Unit) {
    if (this is ScResult.Success) {
        onSuccess(data)
    }
}

/**
 * 单独处理请求失败结果
 */
inline fun <reified T> ScResult<T>.doFailure(onError: (Throwable) -> Unit) {
    if (this is ScResult.Error) {
        onError(throwable)
    }
}


/**
 * 处理返回值
 * 参数标记为crossinline后，不允许直接return返回包含lambda的函数
 */
inline fun <reified T> ScResult<T>.checkResult(crossinline onSuccess: (T) -> Unit,crossinline onError: (ResponseThrowable) -> Unit) {
    if (this is ScResult.Success) {
        onSuccess(data)
    } else if (this is ScResult.Error) {
        onError(throwable)
    }
}
